import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';

export interface res {
  code: number;
  msg: string;
  data: object;
}

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.less'],
})
export class AppComponent {
  constructor(private http: HttpClient) {}
  ngOnInit(): void {
    //Called after the constructor, initializing input properties, and the first call to ngOnChanges.
    //Add 'implements OnInit' to the class.
  }

  files = [];
  fileChange(evt: any) {
    this.files = evt.target.files;
  }

  preUrl: string = 'http://127.0.0.1:8080/user';
  user: any = { username: '伶念', age: 6, classname: 'Class One' };

  jsonPostBody() {
    this.http
      .post(`${this.preUrl}/postUserInfo`, this.user)
      .subscribe((res) => {
        console.log(res);
      });
  }

  formPostBody() {
    const form = new FormData();
    for (let key of Object.keys(this.user)) {
      form.append(key, this.user[key]);
    }
    this.http.post(`${this.preUrl}/postFormUserInfo`, form).subscribe((res) => {
      console.log(res);
    });
  }

  formPostQuery() {
    const form = new FormData();
    this.http
      .post(`${this.preUrl}/postFormUserInfo`, form, { params: this.user })
      .subscribe((res) => {
        console.log(res);
      });
  }

  postFormUserModel() {
    const form = new FormData();
    for (let key of Object.keys(this.user)) {
      form.append(key, this.user[key]);
    }
    for (let file of this.files) {
      form.append('files', file);
    }

    this.http
      .post(`${this.preUrl}/postFormUserModel`, form, {
        // headers: {
        //   enctype: 'multipart/form-data',
        // },
      })
      .subscribe((res) => {
        console.log(res);
      });
  }

  // get传值

  getPath() {
    const { username, age } = this.user;
    this.http.get(`${this.preUrl}/${username}/${age}`).subscribe((res) => {
      console.log(res);
    });
  }
  getQuery() {
    this.http
      .get(`${this.preUrl}/getQuery`, { params: this.user })
      .subscribe((res) => {
        console.log(res);
      });
  }
}
